package com.ruoyi.api.controller;


import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ruoyi.api.common.AppController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;

/**
 * @ClassName PayController
 * @Author hupeng <610796224@qq.com>
 * @Date 2019/9/26
 **/


@RestController
@Api(value = "支付模块", tags = "支付模块", description = "支付模块")
public class PayController extends AppController {

    @Autowired
    private  WxPayService wxPayService;

    /**
     * 调用统一下单接口，并组装生成支付所需参数对象.
     *
     * @param request 统一下单请求参数
     * @param <T>     请使用{@link com.github.binarywang.wxpay.bean.order}包下的类
     * @return 返回 {@link com.github.binarywang.wxpay.bean.order}包下的类对象
     */
    @PostMapping(value = "/shop/pay-do-pay")
    public Object doPay(@Validated @RequestBody String jsonStr) {


        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
        orderRequest.setBody("商品购买");
        orderRequest.setOutTradeNo("123123132123");
        BigDecimal bigDecimal = new BigDecimal(100);
        orderRequest.setTotalFee(1000);//元转成分
        orderRequest.setOpenid("openid");
        orderRequest.setSpbillCreateIp("127.0.0.1");
        orderRequest.setNotifyUrl("https://app2.dayouqiantu.cn/shop/notify");
        orderRequest.setTradeType("JSAPI");
        try {
            WxPayUnifiedOrderResult orderResult = wxPayService.unifiedOrder(orderRequest);
            return writeResultRep(orderResult);
        } catch (WxPayException e) {
            return toResponsFail("系统错误");
        }
    }

    @PostMapping(value = "/shop/notify")
    @ApiOperation(value = "异步通知", notes = "异步通知")
    public String payNotify(@RequestBody String xmlData) {
        try {
            WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);
            String orderNo = notifyResult.getOutTradeNo();
            /*处理业务逻辑*/
            return WxPayNotifyResponse.success("处理成功!");
        } catch (WxPayException e) {

            return WxPayNotifyResponse.fail(e.getMessage());
        }


    }


}
